package com.shundr.auth.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.shundr.auth.channel.R;
import com.shundr.auth.base.BaseActivity;
import com.shundr.auth.common.util.Base64Util;
import com.shundr.auth.common.util.PictureUtil;
import com.shundr.auth.common.util.ProgressDialogHelper;
import com.shundr.auth.common.util.RegexUtil;
import com.shundr.auth.frame.db.model.PictureInfo;
import com.shundr.auth.frame.http.LHttpRequest;
import com.shundr.auth.frame.util.JsonUtil;
import com.shundr.auth.frame.util.LLogger;
import com.shundr.auth.frame.util.StringUtil;
import com.shundr.auth.frame.util.ToastHelper;
import com.shundr.auth.user.http.UserRequest;

public class AuthDriverActivity extends BaseActivity implements OnClickListener {

	private EditText etName;
	private EditText etID;

	private ImageView btnID;
	private ImageView btnDriver;

	private Button btnSubmit;

	private PictureInfo mPIDInfo;// 身份证
	private PictureInfo mPTruckInfo;// 营运证

	private List<PictureInfo> mPictures = new ArrayList<PictureInfo>();

	private int flag = 0;

	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESULT = 3;// 结果
	public static final String IMAGE_UNSPECIFIED = "image/*";

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			ProgressDialogHelper.dismiss();
			super.handleMessage(msg);
			switch (msg.what) {
			case UserRequest.DRIVER_AUTH_COMMIT_SUCCESSED:
				ToastHelper.toastShort(mContext, "认证提交成功，还可以上传头像或者添加车辆。");
				break;
			case LHttpRequest.REQUEST_FAILED:
				ToastHelper.toastShort(mContext, (String) msg.obj);
				break;

			default:
				break;
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		btnRight.setVisibility(View.VISIBLE);
		setContentView(R.layout.activity_auth_driver);
		etName = (EditText) findViewById(R.id.et_name);
		etID = (EditText) findViewById(R.id.et_ID);

		btnID = (ImageView) findViewById(R.id.btn_ID);
		btnDriver = (ImageView) findViewById(R.id.btn_driver);

		btnID.setOnClickListener(this);
		btnDriver.setOnClickListener(this);

		btnRight.setText("上传头像");
		btnRight.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				submitInfo(false);
				startActivity(new Intent(mContext, UserInfoActivity.class));
			}
		});

		btnSubmit = (Button) findViewById(R.id.btn_submit);
		btnSubmit.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ProgressDialogHelper.show(mContext, "正在提交认证,请稍后...");
				submitInfo(true);
			}
		});
	}

	private void submitInfo(boolean showTip) {
		if (check(showTip)) {
			mPictures.clear();
			if (mPIDInfo != null) {
				mPictures.add(mPIDInfo);
			}
			if (mPTruckInfo != null) {
				mPictures.add(mPTruckInfo);
			}
			String json = JsonUtil.toJson(mPictures);
			LLogger.e(json);
			new UserRequest(mContext, mHandler).commitDriverAuth(etName
					.getText().toString(), etID.getText().toString(), json);
		}
	}

	@Override
	protected void onDestroy() {
		releaseImageView(btnID);
		releaseImageView(btnDriver);
		super.onDestroy();
	}

	private boolean check(boolean showTip) {
		if (StringUtil.isNull(etName.getText().toString())) {
			if (showTip) {
				etName.requestFocus();
				ToastHelper.toastShort(mContext, "请填写真实姓名");
			}
			return false;
		}
		if (StringUtil.isNull(etID.getText().toString())) {
			if (showTip) {
				etID.requestFocus();
				ToastHelper.toastShort(mContext, "请填写身份证号码");
			}

			return false;
		}

		if (!RegexUtil.CheckIDNum(etID.getText().toString())) {

			if (showTip) {
				etID.requestFocus();
				ToastHelper.toastShort(mContext, "请填写正确的身份证号码");
			}

			return false;
		}

		// if (mPIDInfo == null) {
		// ToastHelper.toastShort(mContext, "请选择身份证件");
		// return false;
		// }
		// if (mPTruckInfo == null) {
		// ToastHelper.toastShort(mContext, "请选择驾驶证");
		// return false;
		// }
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		Uri data2 = null;
		if (data == null) {
			data2 = PictureUtil.getImageUri();
		} else {
			data2 = data.getData();
		}
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case PictureUtil.PHOTO_PICKED_WITH_DATA:
				intent.setDataAndType(data2, "image/*");
				intent.putExtra("crop", true);
				// 设置裁剪尺寸
				intent.putExtra("aspectX", 1.5);
				intent.putExtra("aspectY", 1);
				intent.putExtra("outputX", 375);
				intent.putExtra("outputY", 250);
				intent.putExtra("return-data", true);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						PictureUtil.getImageCaiUri());
				startActivityForResult(intent, PictureUtil.PHOTO_CROP);
				break;
			case PictureUtil.CAMERA_WITH_DATA:
				data2 = PictureUtil.getCameraImageCaiUri();
				intent.setDataAndType(data2, "image/*");
				intent.putExtra("crop", true);
				intent.putExtra("aspectX", 1.5);
				intent.putExtra("aspectY", 1);
				intent.putExtra("outputX", 375);
				intent.putExtra("outputY", 250);
				intent.putExtra("return-data", true);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						PictureUtil.getImageCaiUri());
				startActivityForResult(intent, PictureUtil.PHOTO_CROP);
				break;
			case PictureUtil.PHOTO_CROP:
				Bundle bundle = data.getExtras();
				Bitmap myBitmap = (Bitmap) bundle.get("data");
				File file = Base64Util.saveBitmapToFile(myBitmap);
				PictureInfo info = new PictureInfo();
				info.setFileBase64Body(Base64Util.encodeImage(myBitmap));
				myBitmap.recycle();
				info.setFilename(PictureUtil.getCharacterAndNumber() + ".png");
				if (flag == 0) {
					info.setType(PictureInfo.FileType.citizen);
					mPIDInfo = info;
					ImageLoader.getInstance().displayImage(
							"file://" + file.getAbsolutePath(), btnID);
				} else if (flag == 1) {
					info.setType(PictureInfo.FileType.truck);
					mPTruckInfo = info;
					ImageLoader.getInstance().displayImage(
							"file://" + file.getAbsolutePath(), btnDriver);
				}
				break;
			default:
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void startPhotoZoom(Uri uri) {
		try {
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
			intent.putExtra("crop", "true");
			// aspectX aspectY 是宽高的比例
			intent.putExtra("aspectX", 1.5);
			intent.putExtra("aspectY", 1);
			// outputX outputY 是裁剪图片宽高
			intent.putExtra("outputX", 600);
			intent.putExtra("outputY", 400);
			intent.putExtra("return-data", true);
			startActivityForResult(intent, PHOTORESULT);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_ID:
			flag = 0;
			break;
		case R.id.btn_driver:
			flag = 1;
			break;
		default:
			break;
		}
		PictureUtil.doPickPhotoAction(mContext);
	}
}
